package com.hairline.hairlinemarket.controller;

import com.hairline.hairlinemarket.bean.MarketCart;
import com.hairline.hairlinemarket.bean.MarketUser;
import com.hairline.hairlinemarket.bean.common.BaseRespVo;
import com.hairline.hairlinemarket.bean.vo.CartVo;
import com.hairline.hairlinemarket.service.CartService;
import com.hairline.hairlinemarket.service.GoodsProductService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.IDN;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:杨小凯
 * Date:2023-04-21 16:03
 * Description:<描述>
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private GoodsProductService goodsProductService;

    /**
     * user对应的购物车数量
     *
     * @return
     */
    @RequestMapping("goodscount")
    public BaseRespVo goodsCount() {
        // TODO 获取信息
        Subject subject = SecurityUtils.getSubject();
        subject.getPrincipal();
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            // 拿到了个人信息
            Integer userId = principal.getId();
            // 查询购物车中该用户id的物品数量
            BigDecimal goodsCount = cartService.selectCountByUserId(userId);

            return BaseRespVo.ok(goodsCount);
        }
        return BaseRespVo.ok(0);
    }

    // TODO 需要增加事务
    @Transactional
    @RequestMapping("/add")
    public BaseRespVo add(@RequestBody Map map) {
        Integer goodsId = (Integer) map.get("goodsId");
        Integer number = (Integer) map.get("number");
        Integer productId = (Integer) map.get("productId");

        System.out.println(goodsId);
        // 获取信息
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        System.out.println(session.getId());
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            // 拿到了个人id信息
            Integer userId = principal.getId();
            // 根据userId以及productId查询购物车中是否有同样的产品
            boolean flag = cartService.selectExist(userId, productId);
            if (flag) {
                // 存在,更新cart中的number
                cartService.updateNumber(userId,number, productId);
            } else {
                // 向cart中添加插入数据
                cartService.insertData(userId, goodsId, number, productId);
            }
            // 减少库存,需要根据goodsId和specifications去修改
            goodsProductService.updateStock(userId, goodsId, number, productId);

            BigDecimal count = cartService.selectCountByUserId(userId);

            return BaseRespVo.ok(count);
        }
        return BaseRespVo.fail("请先登录");
    }


    /**
     * 购物车
     */
    @RequestMapping("index")
    public BaseRespVo index() {
        Map<String, Object> map = new HashMap<>();
        // 获取信息
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            // 拿到了个人id信息
            Integer userId = principal.getId();

            List<MarketCart> cartList = cartService.selectByUserId(userId);

            Map<String, BigDecimal> cartTotal = cartService.selectTotal(userId);

            map.put("cartList", cartList);
            map.put("cartTotal", cartTotal);
        }
        return BaseRespVo.ok(map);
    }

    @RequestMapping("/checked")
    public BaseRespVo checked(@RequestBody Map map) {
        // Integer[] productIds,@RequestBody Integer isChecked
        Integer isChecked = (Integer) map.get("isChecked");
        ArrayList productIds = (ArrayList) map.get("productIds");

        Map<String, Object> reslutMap = new HashMap<>();
        // 获取信息
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            // 拿到了个人id信息
            Integer userId = principal.getId();
            // 修改cart数据库中的checked
            Integer i = cartService.updateChecked(userId, isChecked, productIds);

            List<MarketCart> cartList = cartService.selectByUserId(userId);

            Map<String, BigDecimal> cartTotal = cartService.selectTotal(userId);

            reslutMap.put("cartList", cartList);
            reslutMap.put("cartTotal", cartTotal);
        }
        return BaseRespVo.ok(reslutMap);
    }
    /*@RequestMapping("/checked")
    public void checked(@RequestBody Map map) {
        // 获取信息
        System.out.println(map);
    }*/

    @RequestMapping("/fastadd")
    public BaseRespVo fastadd(@RequestBody Map map) {
        Integer goodsId = (Integer) map.get("goodsId");
        Integer number = (Integer) map.get("number");
        Integer productId = (Integer) map.get("productId");

        // 获取信息
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            // 拿到了个人id信息
            Integer userId = principal.getId();
            // 根据userId以及productId删除数据库中的信息
            cartService.deleteByUPId(userId, productId);

            // 向cart中添加插入数据
            cartService.insertData(userId, goodsId, number, productId);
            // 查询该条数据的id
            Integer id = cartService.selectByUPId(userId, productId);
            // 减少库存,需要根据goodsId和specifications去修改
            goodsProductService.updateStock(userId, goodsId, number, productId);
            return BaseRespVo.ok(id);
        }

        return BaseRespVo.fail("请先登录");
    }


    @RequestMapping("/checkout")
    public BaseRespVo checkout(CartVo cartVo) {

        Map entity = cartService.selectCartReslute(cartVo);

        return BaseRespVo.ok(entity);
    }


    @RequestMapping("/update")
    public BaseRespVo update(@RequestBody Map map){
        // 购物车中该商品的id
        Integer id = (Integer) map.get("id");
        Integer goodsId = (Integer) map.get("goodsId");
        Integer number = (Integer) map.get("number");
        Integer productId = (Integer) map.get("productId");
        // 修改库存
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return BaseRespVo.fail("请先登录");
        }
        MarketUser principal = (MarketUser) subject.getPrincipal();
        boolean updateStock = goodsProductService.updateStock(principal.getId(), goodsId, number, productId);

        // 更新购物车
        cartService.updateNumberById(id,number);

        return BaseRespVo.ok();
    }

    @RequestMapping("/delete")
    public BaseRespVo delete(@RequestBody Map<String,List<Integer>> hashMap){

        List<Integer> productIds = hashMap.get("productIds");
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();
        // 删除购物车中的数据（逻辑删除）
        for (Integer productId : productIds) {
            cartService.deleteByUPId(user.getId(),productId);
        }

        // 需要更新库存
        goodsProductService.updateAddStock(user.getId(),productIds);

        HashMap<String, Object> map = new HashMap<>();
        List<MarketCart> cartList = cartService.selectByUserId(user.getId());

        Map<String, BigDecimal> cartTotal = cartService.selectTotal(user.getId());

        map.put("cartList", cartList);
        map.put("cartTotal", cartTotal);

        return BaseRespVo.ok(map);
    }
}
